package com.my.aslife.controller;

import com.my.aslife.module.common.ErrorCode;
import com.my.aslife.module.common.ResponseResult;
import com.my.aslife.utils.minio.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author mayuan
 * @description FileController
 */
@RestController
@RequestMapping("/api/my/file")
@CrossOrigin
public class FileController {

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping("/upload")
    public ResponseResult upFile(MultipartFile file) {

        return uploadFile(file, "sfz");
    }

    @PostMapping("/download")
    public ResponseResult downloadFile() {
        byte[] bytes = fileStorageService.downLoadFile("http://192.168.200.130:9000/leadnews/2023/02/07/ca86136e54f943229bd2f9d94cbd2210.png");
        return ResponseResult.ok(bytes);
    }

    public ResponseResult uploadFile(MultipartFile file, String prefix){
        if (prefix == null || prefix.length() == 0) {
            prefix = "default";
        }

        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            // 上传文件名为空
            if (originalFilename == null) {
                return ResponseResult.failed(ErrorCode.ILLEGAL_OPERATOR);
            }
            //原始文件名后缀  .jpg
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
            String fileName = UUID.randomUUID() + suffix;

            String url;

            InputStream inputStream = file.getInputStream();
            url = fileStorageService.uploadHtmlFile(prefix, fileName, inputStream);
            return ResponseResult.ok(url);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
